package com.codecrane.core.util;

import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamZipUtil {
    public static InputStream unzipStream(InputStream inputStream) throws IOException {
        //Fail-Fast
        if (inputStream == null) {
            return null;
        }
        //1.Jdk原生Zip流，会因为问价字符集编码不匹配，报MALFORMED错（畸形的）
        //ZipInputStream zipInputStream = new ZipInputStream(inputStream);

        //2.Apach-commons-compress的Zip流，兼容性更好
        ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(inputStream);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (zipInputStream.getNextEntry() != null) {
            int n;
            byte[] buff = new byte[1024];
            while ((n = zipInputStream.read(buff)) != -1) {
                bos.write(buff, 0, n);
            }
        }
        bos.flush();
        bos.close();
        return new ByteArrayInputStream(bos.toByteArray());
    }
}
